﻿using AutoMapper;
using BlogDemo.Api.Authenticate;
using BlogDemo.Api.Models;
using BlogDemo.Application;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace BlogDemo.Api.Controllers
{
    /// <summary>
    /// 鉴权
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        private readonly IAuthenticateService authenticateService;
        public AuthController(IAuthenticateService authenticateService)
        {
            this.authenticateService = authenticateService;
        }

        /// <summary>
        /// 停用 Jwt 授权数据
        /// </summary>
        /// <returns></returns>
        [HttpPost("deactivate")]
        public async Task<IActionResult> CancelAccessToken()
        {
            await authenticateService.DeactivateCurrentAsync();
            return Ok();
        }

        /// <summary>
        /// 获取 Jwt 授权数据
        /// </summary>
        /// <param name="dto">授权用户信息</param>
        [HttpPost("token")]
        [AllowAnonymous]
        public IActionResult Login([FromBody] LoginInputDto dto)
        {
            //Todo：获取用户信息
            var user = new UserDto
            {
                Id = Guid.NewGuid(),
                UserName = "yuiter",
                Role = Guid.Empty,
                Email = "yuiter@yuiter.com",
                Phone = "13912345678",
            };

            if (user == null) return Ok(new { Access = "无权访问", Type = "Bearer" });

            var jwt = authenticateService.Create(user);

            return Ok(new { Access = jwt.Token, Type = "Bearer" });
        }

        /// <summary>
        /// 刷新 Jwt 授权数据
        /// </summary>
        /// <param name="dto">刷新授权用户信息</param>
        /// <returns></returns>
        [HttpPost("refresh")]
        public async Task<IActionResult> RefreshAccessTokenAsync([FromBody] LoginInputDto dto)
        {
            //Todo：获取用户信息
            var user = new UserDto
            {
                Id = Guid.NewGuid(),
                UserName = "yuiter",
                Role = Guid.Empty,
                Email = "yuiter@yuiter.com",
                Phone = "13912345678",
            };

            if (user == null)
                return BadRequest(new { Access = "无权访问", Type = "Bearer" });

            var jwt = await authenticateService.RefreshAsync(dto.Token, user);

            return Ok(new { Access = jwt.Token, Type = "Bearer" });
        }

    }
}
